<template>
    <van-cell class="order-detail-shipment" title-class="order-detail-shipment-title"
              :clickable="tracked"
              @click="handleRouteToOrderShipments">
        <template #icon>
            <van-icon name="logistics" :size="18"/>
        </template>
        <template #title>
            <div class="order-detail-shipment-l1">{{tracked ? latestEvent.message : "无需物流"}}</div>
        </template>
        <template #label v-if="tracked">
            {{latestEvent.occurredTime}}
        </template>
        <template #right-icon v-if="tracked">
            <van-icon name="arrow" style="align-self: center"/>
        </template>
    </van-cell>
</template>

<script>
  import { Cell, Icon, Skeleton, Toast } from "vant"
  import * as _ from "lodash"
  import { message, order, shipping } from "@mall/api-services"

  export default {
    name: "OrderDetailShipment",
    components: {
      [Cell.name]: Cell,
      [Icon.name]: Icon,
      [Skeleton.name]: Skeleton,
    },
    props: {
      order: Object,
    },
    computed: {
      tracked() {
        const { trackingNumber } = this.shipment
        return !_.isEmpty(trackingNumber)
      },
      shipment() {
        const { order: aOrder } = this
        const { shipments } = aOrder
        if (_.isEmpty(shipments)) {
          return new order.Shipment()
        }
        const shipment = _.find(shipments, aShipment => !_.isEmpty(aShipment.trackingNumber))
        return _.isUndefined(shipment) ? _.first(shipments) : shipment
      },
    },
    watch: {
      shipment(shipment) {
        this.refreshTracking(shipment)
      },
    },
    data() {
      return {
        latestEvent: new shipping.TrackingEvent(),
      }
    },
    created() {
      this.refreshTracking(this.shipment)
    },
    methods: {
      handleRouteToOrderShipments() {
        const { order: aOrder, tracked } = this
        if (tracked) {
          this.$router.push(`/orders/${aOrder.id}/shipments`)
        }
      },
      refreshTracking(shipment) {
        const { shippingProvider, trackingNumber } = shipment
        if (_.isEmpty(shippingProvider) || _.isEmpty(trackingNumber)) {
          return
        }
        shipping.TrackingService
          .getTrack(shippingProvider, trackingNumber)
          .then(track => this.latestEvent = _.first(track.events))
          .catch(({ response }) => Toast(message.getResponseMessage(response)))
      },
    },
  }
</script>

<style lang="scss" scoped>
    .order-detail-shipment {
        padding: 12px 9px;

        &:after {
            left: 0;
        }

        .order-detail-shipment-title {
            margin-left: 9px;
        }

        .order-detail-shipment-l1 {
            font-weight: 700;
            line-height: 1rem;
        }
    }
</style>
